package com.tjbklx1.redis.chap05;

import com.tjbklx1.redis.JedisUtil;

import redis.clients.jedis.Jedis;

/**
 * 使用Redis存储配置信息
 * @author tjbklx1
 * @date 2018-12-6
 */
public class App57_UnderMaintenance {
	
	public static void main(String[] args) {
		Jedis conn = JedisUtil.getJedisWithDB();
		try {
			new App57_UnderMaintenance().testIsUnderMaintenance(conn);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void testIsUnderMaintenance(Jedis conn) throws InterruptedException {
		System.out.println("\n----- testIsUnderMaintenance -----");
		System.out.println("Are we under maintenance (we shouldn't be)? " + isUnderMaintenance(conn));
		conn.set("is-under-maintenance", "yes"); //设置参数
		System.out.println("We cached this, so it should be the same: " + isUnderMaintenance(conn));
		Thread.sleep(2000); // sleep一个时间之后,度过时间差
		System.out.println("But after a sleep, it should change: " + isUnderMaintenance(conn));
		System.out.println("Cleaning up...");
		conn.del("is-under-maintenance"); //删除参数
		Thread.sleep(1000);
		System.out.println("Should be False again: " + isUnderMaintenance(conn));
	}

	private long lastChecked;
	private boolean underMaintenance;

	public boolean isUnderMaintenance(Jedis conn) {
		if (lastChecked < System.currentTimeMillis() - 1000) {  // 设置一个时间差
			lastChecked = System.currentTimeMillis();
			String flag = conn.get("is-under-maintenance"); //获取参数
			underMaintenance = "yes".equals(flag);
		}
		return underMaintenance;
	}
}
